package com.uphone.magicleafteacher.pro.activity;

import android.arch.lifecycle.LifecycleOwner;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.radish.baselibrary.Intent.IntentData;
import com.radish.baselibrary.dialog.RadishDialog;
import com.radish.baselibrary.navigationbar.DefaultNavigationBar;
import com.radish.framelibrary.view.glide.GlideUtils;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.uphone.magicleafteacher.MyApp;
import com.uphone.magicleafteacher.R;
import com.uphone.magicleafteacher.base.BaseGActivity;
import com.uphone.magicleafteacher.http.ApiService;
import com.uphone.magicleafteacher.http.FailureConsumer;
import com.uphone.magicleafteacher.http.RequestBodyUtil;
import com.uphone.magicleafteacher.http.RxSchedulers;
import com.uphone.magicleafteacher.http.SuccessfulConsumer;
import com.uphone.magicleafteacher.util.CommonUtil;
import com.uphone.magicleafteacher.util.StickerTask;
import com.uphone.magicleafteacher.vo.WorkcorrectionEvent;
import com.xinlan.imageeditlibrary.editimage.utils.BitmapUtils;
import com.xinlan.imageeditlibrary.editimage.view.CropImageView;
import com.xinlan.imageeditlibrary.editimage.view.CustomPaintView;
import com.xinlan.imageeditlibrary.editimage.view.RotateImageView;
import com.xinlan.imageeditlibrary.editimage.view.StickerView;
import com.xinlan.imageeditlibrary.editimage.view.TextStickerView;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouch;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouchBase;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class WorkcorrectioningActivity extends BaseGActivity {

    @BindView(R.id.main_image)
    public ImageViewTouch mainImage;
    @BindView(R.id.sticker_panel)
    StickerView mStickerView;
    @BindView(R.id.crop_panel)
    CropImageView mCropPanel;
    @BindView(R.id.rotate_panel)
    RotateImageView mRotatePanel;
    @BindView(R.id.text_sticker_panel)
    TextStickerView mTextStickerView;
    @BindView(R.id.custom_paint_view)
    CustomPaintView mPaintView;
    @BindView(R.id.work_space)
    FrameLayout workSpace;
    @BindView(R.id.iv_edit1)
    ImageView ivEdit1;
    @BindView(R.id.iv_edit2)
    ImageView ivEdit2;
    @BindView(R.id.iv_edit3)
    ImageView ivEdit3;
    @BindView(R.id.ll_edit2)
    LinearLayout llEdit2;
    @BindView(R.id.dialog_edit)
    EditText dialogEdit;
    @BindView(R.id.dialog_submit)
    Button dialogSubmit;
    @BindView(R.id.fl_edit)
    FrameLayout flEdit;
    @IntentData
    private String filePath;
    @IntentData
    private String[] filePaths;
    @IntentData
    private String saveFilePath;
    @IntentData
    private int id;
    @IntentData
    private int type; // 0:作业批改，1:阅读点评
    private Context mContext;
    private String jifen;
    private int index;
    private TextView rightTitle;

    @Override
    protected void initBundle() {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_work_correcting;
    }

    private int imageWidth, imageHeight;// 展示图片控件 宽 高

    @Override
    protected void initView() {
        mContext = this;
        llEdit2.setVisibility(View.GONE);
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels / 2;
        imageHeight = metrics.heightPixels / 2;
        mTextStickerView.setTextColor(Color.RED);
        this.mPaintView.setWidth(SizeUtils.dp2px(5));
    }

    private void editDialog() {
        new RadishDialog.Builder(this)
                .setFullWidth()
                .setView(R.layout.dialog_edit)
                .setFocus(R.id.dialog_edit)
                .setClick(R.id.dialog_submit, (dialog, view) -> {
                    EditText dialogEdit = dialog.findViewById(R.id.dialog_edit);
                    if (CommonUtil.checkViewEmpty("请输入积分数", dialogEdit)) {
                        return;
                    }
                    dialog.dismiss();
                    jifen = dialogEdit.getText().toString().trim();
                    showLoading();
                    savePaintImage();
                })
                .show();
    }

    private SaveCustomPaintTask mSavePaintImageTask;

    /**
     * 文字合成任务
     * 合成最终图片
     */
    private final class SaveCustomPaintTask extends StickerTask {

        public SaveCustomPaintTask(WorkcorrectioningActivity activity) {
            super(activity);
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);

            if (mPaintView.getPaintBit() != null) {
                canvas.drawBitmap(mPaintView.getPaintBit(), 0, 0, null);
            }
            canvas.restore();
        }

        @Override
        public void onPostResult(Bitmap result) {
            mPaintView.reset();
            changeMainBitmap(result, true);
            doSaveImage();
        }
    }//end inner class

    /**
     * 保存涂鸦
     */
    public void savePaintImage() {
        if (mSavePaintImageTask != null && !mSavePaintImageTask.isCancelled()) {
            mSavePaintImageTask.cancel(true);
        }

        mSavePaintImageTask = new SaveCustomPaintTask(this);
        mSavePaintImageTask.execute(mainBitmap);
    }

    @Override
    protected void initTitle() {
        DefaultNavigationBar navigationBar = initTitle("开始批改", "完成", v -> {
            if (TextUtils.equals("完成", rightTitle.getText().toString().trim())) {
                editDialog();
            } else {
                showLoading();
                savePaintImage();
            }
        });
        rightTitle = (TextView) navigationBar.getRightTitle();
        if (type == 0 && filePaths.length > 1) {
            rightTitle.setText("下一步");
        }
        rightTitle.setTextColor(getResources().getColor(R.color.themecolor));
    }

    private SaveImageTask mSaveImageTask;

    /**
     * 保存图像
     * 完成后退出
     */
    private final class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))
                saveFilePath = getFilesDir() + String.valueOf(System.currentTimeMillis()) + "temp.png";

            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            closeLoading();
        }

        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            closeLoading();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoading();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                remarkHomework();
            } else {
                closeLoading();
                Toast.makeText(mContext, "图片生成失败", Toast.LENGTH_SHORT).show();
            }
        }
    }//end inner class

    List<File> fileList = new ArrayList();

    private void remarkHomework() {
        if (TextUtils.isEmpty(saveFilePath))
            saveFilePath = getFilesDir() + String.valueOf(System.currentTimeMillis()) + "temp.png";
        File file = new File(CommonUtil.getStr(saveFilePath));
        if (file == null || !file.exists()) {
            ToastUtils.showShort("生成图片失败");
            closeLoading();
            return;
        }
        if (type == 0) {
            fileList.add(file);
            if (index < filePaths.length - 1) {
                mPaintView.setVisibility(View.GONE);
                index++;
                saveFilePath = "";
                if (index == filePaths.length - 1)
                    rightTitle.setText("完成");
                initData();
                return;
            }

//            ImageView iv = findView(R.id.iv_show);
//            ImageView iv1 = findView(R.id.iv_show1);
//            iv.setBackgroundColor(Color.BLACK);
//            iv1.setBackgroundColor(Color.BLACK);
//            LogUtils.e(" fileList.get(0):"+ fileList.get(0).getAbsolutePath()+"    fileList.get(1):"+ fileList.get(1).getAbsolutePath());
//            GlideUtils.getInstance().loadNormalImageNoCache(WorkcorrectioningActivity.this, fileList.get(0), iv);
//            GlideUtils.getInstance().loadNormalImageNoCache(WorkcorrectioningActivity.this, fileList.get(1), iv1);
//            return;
        }
        Map<String, RequestBody> params = new HashMap<>();
        params.put("teacherId", RequestBodyUtil.convertToRequestBody(CommonUtil.getTeacherId()));
        params.put("jifen", RequestBodyUtil.convertToRequestBody(jifen + ""));
        MultipartBody.Part part = RequestBodyUtil.filesToMultipartBodyPart("file", file);
        ApiService apiService = MyApp.apiService(ApiService.class);
        Observable<ResponseBody> observable = null;
        switch (type) {
            case 0:
                List<MultipartBody.Part> fileLists = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    MultipartBody.Part part1 = RequestBodyUtil.filesToMultipartBodyPart("file", fileList.get(i));
                    fileLists.add(part1);
                }
                params.put("processId", RequestBodyUtil.convertToRequestBody(id + ""));
                observable = apiService.remarkHomework(params, fileLists);
                break;
            case 1:
                params.put("readId", RequestBodyUtil.convertToRequestBody(id + ""));
                observable = apiService.remarkBookRead(params, part);
                break;
            case 2:
                params.put("answerId", RequestBodyUtil.convertToRequestBody(id + ""));
                observable = apiService.remarkRepeatWork(params, part);
                break;
        }
        observable.compose(RxSchedulers.io_main())
                .doOnSubscribe(d -> {
                    showLoading();
                })
                .doFinally(() -> {
                    closeLoading();
                })
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) this)))
                .subscribe(new SuccessfulConsumer() {
                    @Override
                    public void success(String jsonObject) {
                        String msg = "";
                        switch (type) {
                            case 0:
                                msg = "批改成功";
                                break;
                            case 1:
                                msg = "点评成功";
                                break;
                            case 2:
                                msg = "批改成功";
                                break;
                        }
                        EventBus.getDefault().post(new WorkcorrectionEvent());
                        CommonUtil.quitActivity(WorkcorrectioningActivity.this, msg);
                    }
                }, new FailureConsumer());
    }


    protected void doSaveImage() {

        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }

        mSaveImageTask = new SaveImageTask();
        mSaveImageTask.execute(mainBitmap);
    }


    @Override
    protected void initData() {
        if (type == 0) {
            loadImage(filePaths[index]);
        } else {
            loadImage(filePath);
        }
    }

    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) {
        if (newBit == null)
            return;

        if (mainBitmap == null || mainBitmap != newBit) {
//            if (needPushUndoStack) {
//                mRedoUndoController.switchMainBit(mainBitmap,newBit);
//                increaseOpTimes();
//            }
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
            editPic();

        }
    }


    private Bitmap mainBitmap;// 底层显示Bitmap

    /**
     * 异步载入编辑图片
     *
     * @param filePath
     */
    public void loadImage(String filePath) {
        Glide.with(this).load(filePath).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                Bitmap bitmap = drawableToBitmap(resource);
                changeMainBitmap(bitmap, false);
                applyTextImage();
            }
        });
    }

    /**
     * 编辑图片
     */
    private void editPic() {
        mainImage.setImageBitmap(mainBitmap);
        mPaintView.setVisibility(View.VISIBLE);
    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public static final Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    @Override
    protected void initListener() {
        dialogEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString().trim();
                mTextStickerView.setText(text);

            }
        });
    }

    @OnClick({R.id.iv_edit1, R.id.iv_edit2, R.id.iv_edit3, R.id.dialog_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_edit1:
                editPic();
                break;
            case R.id.iv_edit2:
                uneditPic();
//                mainImage.setImageBitmap(mainBitmap);
                mTextStickerView.setVisibility(View.VISIBLE);
                llEdit2.setVisibility(View.VISIBLE);
                flEdit.setVisibility(View.GONE);
                mTextStickerView.setEditText(dialogEdit);
                KeyboardUtils.showSoftInput(dialogEdit);
                break;
            case R.id.iv_edit3:
                toggleEraserView();
                break;
            case R.id.dialog_submit:
                applyTextImage();
                KeyboardUtils.hideSoftInput(dialogEdit);
                mTextStickerView.setVisibility(View.GONE);
                flEdit.setVisibility(View.VISIBLE);
                llEdit2.setVisibility(View.GONE);
                editPic();
                break;
        }
    }

    private void uneditPic() {
//        this.mPaintView.setVisibility(View.VISIBLE);
    }

    private void edit2Dialog() {
        RadishDialog radishDialog = new RadishDialog.Builder(this)
                .setFullWidth()
                .setFromBottom(true)
                .setView(R.layout.dialog_edit2)
                .setFocus(R.id.dialog_edit)
                .setClick(R.id.dialog_submit, (dialog, view) -> {
                    applyTextImage();

                })
                .show();
        EditText dialogEdit = radishDialog.findViewById(R.id.dialog_edit);
        mTextStickerView.setEditText(dialogEdit);
        dialogEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString().trim();
                mTextStickerView.setText(text);

            }
        });

    }

    private SaveTextStickerTask mSaveTask;

    private void applyTextImage() {

        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }

        //启动任务
        mSaveTask = new SaveTextStickerTask(this);
        mSaveTask.execute(mainBitmap);
    }

    /**
     * 文字合成任务
     * 合成最终图片
     */
    private final class SaveTextStickerTask extends StickerTask {

        public SaveTextStickerTask(WorkcorrectioningActivity activity) {
            super(activity);
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);
            //System.out.println("scale = " + scale_x + "       " + scale_y + "     " + dx + "    " + dy);
            mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                    mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
            canvas.restore();
        }

        @Override
        public void onPostResult(Bitmap result) {
            mTextStickerView.clearTextContent();
            mTextStickerView.resetView();
            changeMainBitmap(result, true);
        }
    }//end inner class


    public boolean isEraser = false;//是否是擦除模式

    private void toggleEraserView() {
        isEraser = !isEraser;
        updateEraserView();
    }

    private void updateEraserView() {
        ivEdit3.setSelected(isEraser);
        mPaintView.setEraser(isEraser);
    }
}
